package com.applications.codemash;

import java.io.InputStream;
import java.net.URL;
import java.util.List;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ImageView;

import com.applications.codemash.core.BaseActivity;
import com.applications.codemash.core.Constants;
import com.applications.codemash.core.Session;
import com.applications.codemash.core.Speaker;
import com.applications.codemash.core.eventhandlers.ListViewItemClickListener;
import com.applications.codemash.utility.CustomContext;
import com.applications.codemash.utility.CustomListAdapter;

public class SpeakerInfo extends BaseActivity
{
	
	@Override
    public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
    	setContentView(R.layout.speaker_info);
    	
    	showProgressDialog("CodeMash", getString(R.string.loadingSpeakerInformationDialogMessage));
    	
    	Speaker speaker = (Speaker)getIntent().getExtras().get(Constants.SPEAKER_INTENT_KEY);
    	Drawable d = null;
    	if (speaker.getImageUrl() != "")
    	{
    		d = getDrawableForImageUrl(speaker.getImageUrl());
    	}
    	
    	LoadInterface(speaker, d);
    	
    	hideProgresDialog();
	}
	
	private Drawable getDrawableForImageUrl(String imageUrl)
	{
		try
		{
			URL url = new URL(imageUrl);
			InputStream content = (InputStream)url.getContent();
			Drawable d = Drawable.createFromStream(content, "src");
			
			return d;
		}
		catch (Exception ex)
		{
			return null;
		}
	}
	
	private void LoadInterface(Speaker speaker, Drawable d)
	{
		((TextView)findViewById(R.id.txtSpeakerName)).setText(speaker.getName());
    	((TextView)findViewById(R.id.txtSpeakerBio)).setText(Html.fromHtml(speaker.getBiography()));
	    ((TextView)findViewById(R.id.txtSpeakerBlogUrl)).setText("Blog: " + speaker.getBlogUrl());
    	
    	if (d != null)
    	{
    		((ImageView)findViewById(R.id.imgSpeakerPicture)).setImageDrawable(d);
    		((TextView)findViewById(R.id.txtSpeakerTwitter)).setText(Html.fromHtml(
    	    		String.format("<a href='http://www.twitter.com/%1$s'>%1$s</a>", speaker.getTwitterHandle())));
    	    ((TextView)findViewById(R.id.txtSpeakerTwitter)).setMovementMethod(LinkMovementMethod.getInstance());
    	}
    	else
    	{
    		((ImageView)findViewById(R.id.imgSpeakerPicture)).setVisibility(View.GONE);
    	}
    	
    	ListView listView = (ListView)findViewById(R.id.lstSpeakerSessions);
    	listView.setOnItemClickListener(new ListViewItemClickListener(this));
    	
    	List<Session> sessionList = CustomContext.getSessionCache().GetSessionsForSpeaker(speaker.getSpeakerUri());
    	new CustomListAdapter<Session>(sessionList, this, listView);
	}
}